package StudySpringBoot2.controller;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

@Controller
public class JdbcController {
    final
    JdbcTemplate jdbcTemplate;

    public JdbcController(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    // 查询出user表中的所有信息,没有实体类，可以使用万能的map来存
    @GetMapping("/userList")
    @ResponseBody
    public List<Map<String, Object>> userList() {
        String sql = "select * from mybatis.user";
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
        return maps;
    }

    //新增一个用户
    @GetMapping("/addUser")
    public String addUser() {
        //插入语句，注意时间问题
        String sql = "insert into mybatis.user(id, name,pwd) values (6,'zhu','12345')";
        jdbcTemplate.update(sql);
        //查询
        return "updateOk";
    }

    //修改用户信息
    @GetMapping("/update/{id}")
    public String updateUser(@PathVariable("id") int id) {
        //插入语句
        String sql = "update mybatis.user set name=?,pwd=? where id=" + id;
        //数据
        Object[] objects = new Object[2];
        objects[0] = "秦疆";
        objects[1] = "123456";
        jdbcTemplate.update(sql, objects);
        //查询
        return "updateOk";
    }

    //删除用户
    @GetMapping("/delete/{id}")
    public String delUser(@PathVariable("id") int id) {
        //插入语句
        String sql = "delete from mybatis.user  where id=?";
        jdbcTemplate.update(sql, id);
        //查询
        return "deleteOk";
    }
}
